package cn.edkuir.product.web;

import cn.edkuir.product.entity.CategoryEntity;
import cn.edkuir.product.service.CategoryService;
import cn.edkuir.product.vo.Catalog2Vo;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;

@Controller
public class IndexController {
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private RedissonClient redissonClient;


    @GetMapping({"/", "/index.html"})
    public String indexPage(Model model) {
        //TODO 查出所有一级分类
        List<CategoryEntity> categoryEntities = categoryService.findLevelOneCategory();

        model.addAttribute("categorys", categoryEntities);

        return "index";
    }


    @GetMapping("/index/catalog.json")
    @ResponseBody
    public Map<String, List<Catalog2Vo>> getCatalogJson() {
        return categoryService.getCatalogJson();
    }


    @GetMapping("/hello")
    @ResponseBody
    public String hello() {
        RLock lock = redissonClient.getLock("lock");
        //加锁, 阻塞式等待
        /**
         * 1. 锁自动续期, 如果业务时间超长, 运行期间自动续上30s
         * 2. 加锁的业务只有运行完成, 就不会自动续期
         */
        lock.lock();
        try {
            System.out.println("加锁成功" + Thread.currentThread().getName());
            Thread.sleep(30000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            //解锁
            System.out.println("释放锁" + Thread.currentThread().getName());
            lock.unlock();
        }
        return "hello";
    }

}
